package cn.xlmdz.subsoilerinfoquery.ui;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import com.azhon.appupdate.manager.DownloadManager;
import com.kongzue.dialogx.dialogs.InputDialog;
import com.kongzue.dialogx.interfaces.OnInputDialogButtonClickListener;
import com.zhpan.bannerview.BannerViewPager;
import com.zhpan.indicator.enums.IndicatorSlideMode;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.xlmdz.subsoilerinfoquery.R;
import cn.xlmdz.subsoilerinfoquery.adapter.BannerSimpleAdapter;
import cn.xlmdz.subsoilerinfoquery.app.MyApplication;
import cn.xlmdz.subsoilerinfoquery.bean.UpdateBean;
import cn.xlmdz.subsoilerinfoquery.databinding.ActivityMainBinding;
import cn.xlmdz.subsoilerinfoquery.http.ApiServices;
import cn.xlmdz.subsoilerinfoquery.http.NetworkInterceptor;
import cn.xlmdz.subsoilerinfoquery.utils.AppUtil;
import cn.xlmdz.subsoilerinfoquery.utils.ToastUtil;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;
import okhttp3.Cache;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.logging.HttpLoggingInterceptor;
import okio.Buffer;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity {

    private ActivityMainBinding viewBinding;
    private DownloadManager manager;

    private Retrofit mRetrofit;

//    private List<Integer> imageList = Arrays.asList(R.drawable.home_banner_1,R.drawable.home_banner_2,R.drawable.home_banner_3,R.drawable.home_banner_4);
    private List<Integer> imageList = Arrays.asList(R.drawable.home_banner);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        viewBinding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(viewBinding.getRoot());

        queryNewVersion();

        initViews();
    }

    private void initViews() {
        viewBinding.bannerView.registerLifecycleObserver(getLifecycle())
                .setAdapter(new BannerSimpleAdapter())
                .setInterval(5000)
                .setIndicatorVisibility(View.VISIBLE)
                .setIndicatorSlideMode(IndicatorSlideMode.SMOOTH)
                .setIndicatorSliderColor(getResources().getColor(R.color.banner_indicator_normalColor),getResources().getColor(R.color.banner_indicator_checkedColor))
                        .create(imageList);



        viewBinding.llQuerySingle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new InputDialog("作业查询", "请输入终端号码", "确定", "取消", "LM")
                        .setCancelable(false)
                        .setOkButton(new OnInputDialogButtonClickListener<InputDialog>() {
                            @Override
                            public boolean onClick(InputDialog baseDialog, View v, String inputStr) {
                                /*if (inputStr.length() != 7) {
                                    ToastUtil.showTextToast("终端号码长度错误");
                                    return false;
                                }
                                if (!isNumeric(inputStr)) {
                                    ToastUtil.showTextToast("终端号码类型错误");
                                    return false;
                                }*/

                                Intent intent = new Intent(MainActivity.this, QuerySingleActivity.class);
                                intent.putExtra("terminalId", inputStr);
                                startActivity(intent);

                                return false;
                            }
                        })
                        .show();
            }
        });

        viewBinding.llQueryOrg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                startActivity(intent);
            }
        });
    }

    private void queryNewVersion() {
        mRetrofit = new Retrofit.Builder()
                .baseUrl("http://update.xlmyun.cn/")
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
                .client(getHttpClient())
                .build();

        ApiServices services = mRetrofit.create(ApiServices.class);
        Observable<UpdateBean> observable = services.getNewVersion();
        observable.subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<UpdateBean>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull UpdateBean updateBean) {
                        if (updateBean != null) {
                            if (updateBean.getVersionCode() > AppUtil.getVersionCode(MainActivity.this)) {
                                showUpdateDialog(updateBean.getModifyContent(), updateBean.getDownloadUrl());
                            }
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    /**
     * 利用正则表达式判断字符串是否是数字
     *
     * @param str
     * @return
     */
    public boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

    private void showUpdateDialog(String msg, String url) {
        new AlertDialog.Builder(this)
                .setTitle("发现新版本")
                .setMessage(msg)
                .setPositiveButton("升级", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        manager = DownloadManager.getInstance(MainActivity.this);
                        manager.setApkName("ESFileExplorer.apk")
                                .setApkUrl(url)
                                .setSmallIcon(R.mipmap.ic_launcher)
                                .download();
                    }
                }).create().show();
    }

    private OkHttpClient getHttpClient() {
        //日志拦截器
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        //缓存
        int size = 1024 * 1024 * 100;
        File cacheFile = new File(MyApplication.getAppContext().getCacheDir(), "OkHttpCache");
        Cache cache = new Cache(cacheFile, size);

        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(12, TimeUnit.SECONDS)
                .readTimeout(12, TimeUnit.SECONDS)
                .writeTimeout(12, TimeUnit.SECONDS)
                .addNetworkInterceptor(new NetworkInterceptor()) //网络缓存设置
                .addInterceptor(loggingInterceptor)
                .addInterceptor(chain -> { //添加公共请求参数
                    Request request = chain.request();

                    if (request.method().equals("POST")) {//POST公共请求参数
                        Request.Builder requestBuilder = request.newBuilder();
                        RequestBody formBody = new FormBody.Builder()
                                .add("os", "android")
                                .build();

                        String postBodyString = bodyToString(request.body());
                        postBodyString += ((postBodyString.length() > 0) ? "&" : "") + bodyToString(formBody);
                        requestBuilder.post(RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"), postBodyString));
                        request = requestBuilder.build();
                    }
                    return chain.proceed(request);
                })
                .build();

        return client;
    }

    /**
     * post 在body添加参数
     *
     * @param request
     * @return
     */
    private static String bodyToString(final RequestBody request) {
        try {
            final RequestBody copy = request;
            final Buffer buffer = new Buffer();
            if (copy != null)
                copy.writeTo(buffer);
            else
                return "";
            return buffer.readUtf8();
        } catch (final IOException e) {
            return "did not work";
        }
    }

}